
using System;
using System.IO;
using System.Collections.Generic;

using System.CodeDom;
using System.CodeDom.Compiler;

namespace Mono.VisualC.Code {
	public class CodeUnit : CodeContainer {

		public string ManagedNamespace { get; set; }

		public CodeUnit () : base (string.Empty)
		{
		}
		
		public virtual CodeCompileUnit WrapperToCodeDom (CodeDomProvider provider)
		{
			CodeCompileUnit ccu = new CodeCompileUnit ();
			ccu.UserData ["CodeAtom"] = this;

			current_code_provider = provider;
			Visit (ccu);
			current_code_provider = null;

			return ccu;
		}

		internal protected override object InsideCodeCompileUnit (CodeCompileUnit ccu)
		{
			CodeNamespace ns = new CodeNamespace (ManagedNamespace);
			ns.Imports.Add (new CodeNamespaceImport ("Mono.VisualC.Interop"));

			ns.UserData ["CodeCompileUnit"] = ccu;

			ccu.Namespaces.Add (ns);
			return ns;
		}

		internal protected override object InsideCodeNamespace (CodeNamespace ns)
		{
			foreach (var atom in Atoms)
				atom.Visit (ns);

			return null;
		}

		public override string ToString ()
		{
			StringWriter str = new StringWriter ();
			Write (str);
			return str.ToString ();
		}
		
		public override void Write (TextWriter writer)
		{
			writer.WriteLine ("//------------------------------------------------------------------------------");
			writer.WriteLine ("// <auto-generated>");
			writer.WriteLine ("//     This code was generated by a tool.");
			writer.WriteLine ("//     Runtime Version:{0}{1}//", Environment.Version, writer.NewLine);
			writer.WriteLine ("//     Changes to this file may cause incorrect behavior and will be lost if");
			writer.WriteLine ("//     the code is regenerated.");
			writer.WriteLine ("// </auto-generated>");
			writer.WriteLine ("//------------------------------------------------------------------------------{0}", writer.NewLine);

			base.Write (writer);
		}

		public virtual void Save (string fileName)
		{
			using (StreamWriter stream = File.CreateText (fileName)) {
				Write (stream);
			}
		}
	}
}
